package com.site.common;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 验证工具类
 * @author xiaochi
 * @date 2025/9/30
 */
public class ValidatorUtil {

    public static interface Create{}
    public static interface Update{}
    public static interface Select{}
    public static interface Delete{}

	private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	/**
	 * 验证某个对象所有字段
	 *
	 * @param obj
	 * @param <T>
	 * @return
	 */
	public static <T> ValidationResult validateEntity(T obj, Class<?>... groups) {
		ValidationResult result = new ValidationResult();
		//Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
		Set<ConstraintViolation<T>> set = validator.validate(obj, groups);
		if (!set.isEmpty()) {
			result.setHasErrors(true);
			Map<String, String> errorMsg = new HashMap<>();
			for (ConstraintViolation<T> cv : set) {
				errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
                break;
			}
			result.setErrorMsg(errorMsg);
		}
		return result;
	}

	/**
	 * 验证某个对象某个字段
	 *
	 * @param obj
	 * @param propertyName
	 * @param <T>
	 * @return
	 */
	public static <T> ValidationResult validateProperty(T obj, String propertyName, Class<?>... groups) {
		ValidationResult result = new ValidationResult();
		//Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
		Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, groups);
		if (!set.isEmpty()) {
			result.setHasErrors(true);
			Map<String, String> errorMsg = new HashMap<>();
			for (ConstraintViolation<T> cv : set) {
				errorMsg.put(propertyName, cv.getMessage());
			}
			result.setErrorMsg(errorMsg);
		}
		return result;
	}

	/**
	 * 验证结果
	 */
	@Data
	@Builder
	@NoArgsConstructor
	@AllArgsConstructor
	@Accessors(chain = true)
	public static class ValidationResult {
		private Boolean hasErrors = false;
		private Map<String, String> errorMsg;
	}
}
